﻿/********
* 
* 
*  Description:
*  Create By kain.hong at 8/9/2010 3:15:58 PM
*  
*
*  Revision History:
*  Date                  Who                 What
*  
* 
*/
#region namespace

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.ServiceModel;
using System.ServiceModel.Dispatcher;
using System.Diagnostics;

#endregion


namespace Cherry.Agile.ServiceModel.Interceptor
{
    /// <summary>
    /// 定义个ErrorHandling<see cref="System.ServiceModel.Description.IServiceBehavior"/>
    /// </summary>
    public sealed class ErrorHandlingInterceptorAttribute : Attribute, IServiceBehavior
    {
        string _policyName;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="policyName"></param>
        public ErrorHandlingInterceptorAttribute(string policyName)
        {
            _policyName = policyName;
        }

        void IServiceBehavior.AddBindingParameters(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase, System.Collections.ObjectModel.Collection<ServiceEndpoint> endpoints, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
            
        }

        void IServiceBehavior.Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
             
        }
        
        void IServiceBehavior.ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)
        {
            foreach (ChannelDispatcherBase chanDispBase in serviceHostBase.ChannelDispatchers)
            {
                ChannelDispatcher channelDispatcher = chanDispBase as ChannelDispatcher;
                if (channelDispatcher == null)
                    continue;
                Trace.TraceInformation("ErrorHandlingInterceptorAttribute\tapply error handler into service description:" + serviceDescription.Name);
                channelDispatcher.ErrorHandlers.Add(new ErrorHandler(_policyName));
            }
        }
    }
}
